package com.webserver.core;

import com.webserver.controller.ArticleController;
import com.webserver.controller.UserController;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.*;

/**
 * 用于处理请求
 */
public class DispatcherServlet {
    public void service(HttpRequest request, HttpResponse response) {
        String path = request.getRequestURI();

        //首先判断该请求会否为请求一个业务\
        if ("/myweb/regUser".equals(path)) {
            //处理注册
            UserController controller = new UserController();
            controller.reg(request, response);
        } else if ("/myweb/loginUser".equals(path)) {
            UserController controller = new UserController();
            controller.login(request, response);
        } else if ("/myweb/writeArticle".equals(path)) {
            ArticleController controller=new ArticleController();
            controller.writeArticle(request,response);
        } else {
            //如果请求的资源存在并且时一个文件则正确
            File file = new File("./webapps" + path);
            if (file.exists() && file.isFile()) {
                //正确情况
                response.setEntity(file);

            } else {//否则该资源不存在,要响应404
                //没有
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File("webapps/root/404.html");
                response.setEntity(file);
            }
        }


        //如果请求的资源存在并且是一个文件则正确


        //该响应头时告诉浏览器服务端是谁
        response.putHeader("Sevrer", "WebServer");
    }

}
